package fr.utbm.gi.in56.database;

import java.sql.Connection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

/**
 * Servlet implementation class DatabaseServlet
 * 
 * @author Adrien Hoffer & Tarik Belabbas
 */
@WebServlet("/DatabaseServlet")
public abstract class DatabaseServlet extends HttpServlet
{
	/**
	 * Version number associated to the serializable class.
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * The connection to database.
	 */
	private Connection connection;
       
    /**
     * Default constructor.
     * 
     * @see HttpServlet#HttpServlet()
     */
    public DatabaseServlet()
    {
        super();
    }

    /* (non-Javadoc)
     * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
     */
    @Override
	public void init(ServletConfig config) throws ServletException
	{
    	super.init(config);
		ConnectionPool pool		= getConnectionPool();
		this.connection			= pool.getConnection();
	}

	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#destroy()
	 */
	@Override
	public void destroy()
	{
		ConnectionPool pool = getConnectionPool();
		pool.close( this.connection );
	}
	
	/**
	 * Returns the connection pool.
	 * 
	 * @return the connection pool.
	 */
	protected ConnectionPool getConnectionPool()
	{
		ServletContext context	= getServletContext();
		String key				= ConnectionServlet.getPoolKey();
		Object object			= context.getAttribute( key );
	
		return ( ConnectionPool )object;
	}
	
	/**
	 * Returns the connection.
	 * 
	 * @return the connection
	 */
	protected Connection getConnection()
	{
		return this.connection;
	}
}
